{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "package loaded\n"
     ]
    }
   ],
   "source": [
    "\"\"\"\n",
    "Simple Muti_layer Pectron with MNIST\n",
    "author hadxu(hadxu123@gmail.com)\n",
    "\"\"\"\n",
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "%matplotlib inline\n",
    "print 'package loaded'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "#Load MNIST\n",
    "mnist = input_data.read_data_sets('data/',one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Network ready\n"
     ]
    }
   ],
   "source": [
    "#Paremeters\n",
    "learning_rate = 0.001\n",
    "training_epochs = 50\n",
    "batch_size = 100\n",
    "display_step = 1\n",
    "\n",
    "#NetWork Parameters\n",
    "n_hidden_1 = 256\n",
    "n_hidden_2 = 256\n",
    "n_input = 784\n",
    "n_classes = 10\n",
    "\n",
    "x = tf.placeholder('float',[None,n_input])\n",
    "y = tf.placeholder('float',[None,n_classes])\n",
    "\n",
    "#create model\n",
    "def multilayer_perceptron(_X, _weight, _biases):\n",
    "    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X,_weight['h1']),_biases['b1']))\n",
    "    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1,_weight['h2']),_biases['b2']))\n",
    "    return tf.sigmoid(tf.matmul(layer_2,_weight['out']) + _biases['out'])\n",
    "\n",
    "#store layers weight & bias\n",
    "stddev = 0.1\n",
    "weights={\n",
    "    'h1' : tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev=stddev)),\n",
    "    'h2' : tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)),\n",
    "    'out' : tf.Variable(tf.random_normal([n_hidden_2,n_classes],stddev=stddev))\n",
    "}\n",
    "\n",
    "biases = {\n",
    "    'b1' : tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "    'b2' : tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    'out' : tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "\n",
    "#construct model\n",
    "pred = multilayer_perceptron(x,weights,biases)\n",
    "\n",
    "#deinfe loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))\n",
    "optimizer =  tf.train.AdamOptimizer(learning_rate).minimize(cost)\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,'float'))\n",
    "\n",
    "#Initialzing the variables\n",
    "init = tf.initialize_all_variables()\n",
    "print 'Network ready'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#launch the graph\n",
    "sess = tf.Session()\n",
    "sess.run(init)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/050 cost: 1.661144641\n",
      "Training accuracy: 0.900\n",
      "Epoch: 001/050 cost: 1.533657186\n",
      "Training accuracy: 0.920\n",
      "Epoch: 002/050 cost: 1.515018534\n",
      "Training accuracy: 0.920\n",
      "Epoch: 003/050 cost: 1.504359620\n",
      "Training accuracy: 0.970\n",
      "Epoch: 004/050 cost: 1.496003234\n",
      "Training accuracy: 0.970\n",
      "Epoch: 005/050 cost: 1.490515889\n",
      "Training accuracy: 0.970\n",
      "Epoch: 006/050 cost: 1.486174580\n",
      "Training accuracy: 0.960\n",
      "Epoch: 007/050 cost: 1.482079060\n",
      "Training accuracy: 0.990\n",
      "Epoch: 008/050 cost: 1.479586709\n",
      "Training accuracy: 0.990\n",
      "Epoch: 009/050 cost: 1.477284552\n",
      "Training accuracy: 0.990\n",
      "Epoch: 010/050 cost: 1.475122648\n",
      "Training accuracy: 0.980\n",
      "Epoch: 011/050 cost: 1.473801628\n",
      "Training accuracy: 1.000\n",
      "Epoch: 012/050 cost: 1.472447924\n",
      "Training accuracy: 0.990\n",
      "Epoch: 013/050 cost: 1.470643069\n",
      "Training accuracy: 0.980\n",
      "Epoch: 014/050 cost: 1.470068424\n",
      "Training accuracy: 0.990\n",
      "Epoch: 015/050 cost: 1.469698374\n",
      "Training accuracy: 0.980\n",
      "Epoch: 016/050 cost: 1.468393214\n",
      "Training accuracy: 1.000\n",
      "Epoch: 017/050 cost: 1.468351761\n",
      "Training accuracy: 1.000\n",
      "Epoch: 018/050 cost: 1.467327672\n",
      "Training accuracy: 1.000\n",
      "Epoch: 019/050 cost: 1.467175434\n",
      "Training accuracy: 1.000\n",
      "Epoch: 020/050 cost: 1.466315755\n",
      "Training accuracy: 0.990\n",
      "Epoch: 021/050 cost: 1.466374321\n",
      "Training accuracy: 1.000\n",
      "Epoch: 022/050 cost: 1.466165493\n",
      "Training accuracy: 0.990\n",
      "Epoch: 023/050 cost: 1.465727052\n",
      "Training accuracy: 1.000\n",
      "Epoch: 024/050 cost: 1.466085435\n",
      "Training accuracy: 0.980\n",
      "Epoch: 025/050 cost: 1.465146457\n",
      "Training accuracy: 1.000\n",
      "Epoch: 026/050 cost: 1.464996234\n",
      "Training accuracy: 1.000\n",
      "Epoch: 027/050 cost: 1.465071325\n",
      "Training accuracy: 0.990\n",
      "Epoch: 028/050 cost: 1.464862810\n",
      "Training accuracy: 1.000\n",
      "Epoch: 029/050 cost: 1.464822534\n",
      "Training accuracy: 1.000\n",
      "Epoch: 030/050 cost: 1.464570831\n",
      "Training accuracy: 0.980\n",
      "Epoch: 031/050 cost: 1.464999658\n",
      "Training accuracy: 1.000\n",
      "Epoch: 032/050 cost: 1.464551470\n",
      "Training accuracy: 0.990\n",
      "Epoch: 033/050 cost: 1.464156787\n",
      "Training accuracy: 0.990\n",
      "Epoch: 034/050 cost: 1.464627075\n",
      "Training accuracy: 0.990\n",
      "Epoch: 035/050 cost: 1.464379483\n",
      "Training accuracy: 1.000\n",
      "Epoch: 036/050 cost: 1.464478353\n",
      "Training accuracy: 0.990\n",
      "Epoch: 037/050 cost: 1.463863524\n",
      "Training accuracy: 1.000\n",
      "Epoch: 038/050 cost: 1.464186114\n",
      "Training accuracy: 1.000\n",
      "Epoch: 039/050 cost: 1.463900409\n",
      "Training accuracy: 1.000\n",
      "Epoch: 040/050 cost: 1.464501041\n",
      "Training accuracy: 0.980\n",
      "Epoch: 041/050 cost: 1.463875385\n",
      "Training accuracy: 1.000\n",
      "Epoch: 042/050 cost: 1.463923897\n",
      "Training accuracy: 1.000\n",
      "Epoch: 043/050 cost: 1.464127510\n",
      "Training accuracy: 1.000\n",
      "Epoch: 044/050 cost: 1.463973810\n",
      "Training accuracy: 1.000\n",
      "Epoch: 045/050 cost: 1.463883773\n",
      "Training accuracy: 1.000\n",
      "Epoch: 046/050 cost: 1.463819552\n",
      "Training accuracy: 1.000\n",
      "Epoch: 047/050 cost: 1.463979545\n",
      "Training accuracy: 1.000\n",
      "Epoch: 048/050 cost: 1.463685853\n",
      "Training accuracy: 1.000\n",
      "Epoch: 049/050 cost: 1.463971312\n",
      "Training accuracy: 1.000\n",
      "Optimization Finished!\n"
     ]
    }
   ],
   "source": [
    "# Training cycle\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(total_batch):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        # Fit training using batch data\n",
    "        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        # Compute average loss\n",
    "        avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n",
    "    # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))\n",
    "        train_acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        print (\"Training accuracy: %.3f\" % (train_acc))\n",
    "\n",
    "print (\"Optimization Finished!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "acc is 0.980\n"
     ]
    }
   ],
   "source": [
    "#test\n",
    "\n",
    "test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "print 'acc is %.3f' % test_acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#very good"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Network ready\n"
     ]
    }
   ],
   "source": [
    "# let's add some layer\n",
    "#Paremeters\n",
    "learning_rate = 0.001\n",
    "training_epochs = 50\n",
    "batch_size = 100\n",
    "display_step = 1\n",
    "\n",
    "#NetWork Parameters\n",
    "n_hidden_1 = 256\n",
    "n_hidden_2 = 256\n",
    "n_hidden_3 = 256\n",
    "n_hidden_4 = 256\n",
    "n_input = 784\n",
    "n_classes = 10\n",
    "\n",
    "x = tf.placeholder('float',[None,n_input])\n",
    "y = tf.placeholder('float',[None,n_classes])\n",
    "\n",
    "#create model\n",
    "def multilayer_perceptron(_X, _weight, _biases):\n",
    "    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X,_weight['h1']),_biases['b1']))\n",
    "    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1,_weight['h2']),_biases['b2']))\n",
    "    layer_3 = tf.nn.sigmoid(tf.add(tf.matmul(layer_2,_weight['h3']),_biases['b3']))\n",
    "    layer_4 = tf.nn.sigmoid(tf.add(tf.matmul(layer_3,_weight['h4']),_biases['b4']))\n",
    "    return tf.sigmoid(tf.matmul(layer_4,_weight['out']) + _biases['out'])\n",
    "\n",
    "#store layers weight & bias\n",
    "stddev = 0.1\n",
    "weights={\n",
    "    'h1' : tf.Variable(tf.random_normal([n_input,n_hidden_1],stddev=stddev)),\n",
    "    'h2' : tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2],stddev=stddev)),\n",
    "    'h3' : tf.Variable(tf.random_normal([n_hidden_2,n_hidden_3],stddev=stddev)),\n",
    "    'h4' : tf.Variable(tf.random_normal([n_hidden_3,n_hidden_4],stddev=stddev)),\n",
    "    'out' : tf.Variable(tf.random_normal([n_hidden_4,n_classes],stddev=stddev))\n",
    "}\n",
    "\n",
    "biases = {\n",
    "    'b1' : tf.Variable(tf.random_normal([n_hidden_1])),\n",
    "    'b2' : tf.Variable(tf.random_normal([n_hidden_2])),\n",
    "    'b3' : tf.Variable(tf.random_normal([n_hidden_3])),\n",
    "    'b4' : tf.Variable(tf.random_normal([n_hidden_4])),\n",
    "    'out' : tf.Variable(tf.random_normal([n_classes]))\n",
    "}\n",
    "\n",
    "#construct model\n",
    "pred = multilayer_perceptron(x,weights,biases)\n",
    "\n",
    "#deinfe loss and optimizer\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))\n",
    "optimizer =  tf.train.AdamOptimizer(learning_rate).minimize(cost)\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction,'float'))\n",
    "\n",
    "#Initialzing the variables\n",
    "init = tf.initialize_all_variables()\n",
    "print 'Network ready'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/050 cost: 1.680872209\n",
      "Training accuracy: 0.870\n",
      "Epoch: 001/050 cost: 1.520987178\n",
      "Training accuracy: 0.910\n",
      "Epoch: 002/050 cost: 1.502295524\n",
      "Training accuracy: 0.980\n",
      "Epoch: 003/050 cost: 1.492699422\n",
      "Training accuracy: 0.980\n",
      "Epoch: 004/050 cost: 1.485316096\n",
      "Training accuracy: 0.970\n",
      "Epoch: 005/050 cost: 1.482602013\n",
      "Training accuracy: 0.970\n",
      "Epoch: 006/050 cost: 1.478854963\n",
      "Training accuracy: 0.990\n",
      "Epoch: 007/050 cost: 1.477498262\n",
      "Training accuracy: 1.000\n",
      "Epoch: 008/050 cost: 1.476026180\n",
      "Training accuracy: 0.970\n",
      "Epoch: 009/050 cost: 1.474154800\n",
      "Training accuracy: 0.970\n",
      "Epoch: 010/050 cost: 1.472718714\n",
      "Training accuracy: 0.980\n",
      "Epoch: 011/050 cost: 1.471860447\n",
      "Training accuracy: 0.980\n",
      "Epoch: 012/050 cost: 1.471202570\n",
      "Training accuracy: 1.000\n",
      "Epoch: 013/050 cost: 1.470951839\n",
      "Training accuracy: 0.990\n",
      "Epoch: 014/050 cost: 1.470559784\n",
      "Training accuracy: 0.990\n",
      "Epoch: 015/050 cost: 1.469577408\n",
      "Training accuracy: 1.000\n",
      "Epoch: 016/050 cost: 1.469570503\n",
      "Training accuracy: 0.990\n",
      "Epoch: 017/050 cost: 1.468526659\n",
      "Training accuracy: 0.990\n",
      "Epoch: 018/050 cost: 1.468569660\n",
      "Training accuracy: 0.990\n",
      "Epoch: 019/050 cost: 1.468223239\n",
      "Training accuracy: 0.990\n",
      "Epoch: 020/050 cost: 1.467675227\n",
      "Training accuracy: 0.980\n",
      "Epoch: 021/050 cost: 1.467778692\n",
      "Training accuracy: 1.000\n",
      "Epoch: 022/050 cost: 1.467797414\n",
      "Training accuracy: 0.990\n",
      "Epoch: 023/050 cost: 1.466904223\n",
      "Training accuracy: 0.990\n",
      "Epoch: 024/050 cost: 1.466828807\n",
      "Training accuracy: 1.000\n",
      "Epoch: 025/050 cost: 1.466718106\n",
      "Training accuracy: 1.000\n",
      "Epoch: 026/050 cost: 1.466986924\n",
      "Training accuracy: 0.990\n",
      "Epoch: 027/050 cost: 1.466487931\n",
      "Training accuracy: 1.000\n",
      "Epoch: 028/050 cost: 1.466247684\n",
      "Training accuracy: 0.990\n",
      "Epoch: 029/050 cost: 1.465985313\n",
      "Training accuracy: 0.990\n",
      "Epoch: 030/050 cost: 1.466249555\n",
      "Training accuracy: 0.990\n",
      "Epoch: 031/050 cost: 1.465928923\n",
      "Training accuracy: 0.990\n",
      "Epoch: 032/050 cost: 1.466517337\n",
      "Training accuracy: 0.990\n",
      "Epoch: 033/050 cost: 1.466244789\n",
      "Training accuracy: 0.980\n",
      "Epoch: 034/050 cost: 1.465547036\n",
      "Training accuracy: 1.000\n",
      "Epoch: 035/050 cost: 1.465968291\n",
      "Training accuracy: 0.980\n",
      "Epoch: 036/050 cost: 1.465476822\n",
      "Training accuracy: 0.990\n",
      "Epoch: 037/050 cost: 1.465504366\n",
      "Training accuracy: 0.990\n",
      "Epoch: 038/050 cost: 1.466047625\n",
      "Training accuracy: 1.000\n",
      "Epoch: 039/050 cost: 1.465533317\n",
      "Training accuracy: 0.990\n",
      "Epoch: 040/050 cost: 1.465941440\n",
      "Training accuracy: 1.000\n",
      "Epoch: 041/050 cost: 1.465723997\n",
      "Training accuracy: 1.000\n",
      "Epoch: 042/050 cost: 1.464902812\n",
      "Training accuracy: 0.990\n",
      "Epoch: 043/050 cost: 1.466156170\n",
      "Training accuracy: 1.000\n",
      "Epoch: 044/050 cost: 1.466065655\n",
      "Training accuracy: 0.990\n",
      "Epoch: 045/050 cost: 1.465033080\n",
      "Training accuracy: 1.000\n",
      "Epoch: 046/050 cost: 1.465018406\n",
      "Training accuracy: 0.990\n",
      "Epoch: 047/050 cost: 1.464903196\n",
      "Training accuracy: 1.000\n",
      "Epoch: 048/050 cost: 1.465750437\n",
      "Training accuracy: 0.990\n",
      "Epoch: 049/050 cost: 1.464896704\n",
      "Training accuracy: 1.000\n",
      "Optimization Finished!\n"
     ]
    }
   ],
   "source": [
    "#launch the graph\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "# Training cycle\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(total_batch):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        # Fit training using batch data\n",
    "        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        # Compute average loss\n",
    "        avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n",
    "    # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f\" % (epoch, training_epochs, avg_cost))\n",
    "        train_acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        print (\"Training accuracy: %.3f\" % (train_acc))\n",
    "\n",
    "print (\"Optimization Finished!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "acc is 0.981\n"
     ]
    }
   ],
   "source": [
    "test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})\n",
    "print 'acc is %.3f' % test_acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.11+"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
